package com.szcatic.ework.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.szcatic.ework.service.UserService;
import com.szcatic.ework.service.login.LoginService;
import com.szcatic.ework.utils.NetworkUtils;
import com.szcatic.ework.utils.UserAgentUtils;
import com.szcatic.ework.vo.User;
import com.szcatic.ework.vo.other.LoginInfo;

/**
 * RememberMe功能增加session功能
 * @author Administrator
 *
 */
public class RememberMeSessionFilter extends OncePerRequestFilter{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private LoginService loginService;
	@Override
	protected void doFilterInternal(ServletRequest request,
			ServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isRemembered() && subject.getSession().getAttribute("user") == null) {
			//如果是通过记住我功能进入系统，且session中user的信息为空时
			System.out.println(subject.isRemembered() + (String)subject.getPrincipal());
			User user = userService.getUserByUserName((String)subject.getPrincipal());
			subject.getSession().setAttribute("user", user);
			//增加用户登录日志
			submitLoginInfo((HttpServletRequest)request);
		}
		chain.doFilter(request, response);
	}
	
	/**
	 * 提交用户日志
	 */
	private void submitLoginInfo(HttpServletRequest request) {
		
		LoginInfo loginInfo = new LoginInfo();
		Subject subject = SecurityUtils.getSubject();
		User user = (User)subject.getSession().getAttribute("user");
		loginInfo.setUser(user);
		loginInfo.setBrower(UserAgentUtils.getBrowser(request));
		loginInfo.setOs(UserAgentUtils.getOS(request));
		loginInfo.setSessionId(subject.getSession().getId().toString());
		try {
			loginInfo.setIp(NetworkUtils.getIpAddress(request));
		} catch (IOException e) {
			e.printStackTrace();
		}
		loginInfo.setLoginType("2"); //记住我登录
		loginService.insertLoginInfo(loginInfo);
	}

}
